package com.inspur.incubator.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.FileUpToServer;
import com.jcraft.jsch.ChannelSftp;



public class FileUtil {
		  //获取ip地址  
	   
	// private static String FTP_ADDRESS="123.138.111.171";  
	    private static String FTP_ADDRESS=""; 
	    //端口号  
	   
	    // private static String FTP_PORT="53002";  
	    //端口号  
		   
	    private static String FTP_PORT="22";  
	    //用户名  
	 
	    private static String FTP_USERNAME="";  
	    //密码  
	  
	    private static String FTP_PASSWORD="";  
	    //基本路径  
	   
	    private static String FTP_BASEPATH="/data";  
	    private static String FTP_BASEPATH_LOCAL="/data";
	    //private static String FTP_BASEPATH_LOCAL="d:";
	    //下载地址地基础url  
	   
	    /**
	       * 上传文件
	       * @param CommonsMultipartFile[] files
	       * @return String[]文件存储路径数组
	       * 
	       * */  
		  public static   String[] uploadFile(CommonsMultipartFile[] files,HttpServletRequest request)
		  { 		 
	       String[] arrStr=new String[files.length]; 
	       for(int i = 0;i<files.length;i++)
	       {  
	        // System.out.println("fileName---------->" + files[i].getOriginalFilename());           
	          if(!files[i].isEmpty())
	          {  
	              System.currentTimeMillis();  
	              try
	              {  
	              
	            	  SimpleDateFormat format =new SimpleDateFormat("yyyyMMdd");
	          		  SimpleDateFormat format1 =new SimpleDateFormat("yyyyMMddHHmmssSSS");
	          		  new Date();                                
	                  String aa=format.format(new Date());
	                  String path = request.getSession().getServletContext().getRealPath("uploads")+"/"+aa;
	                  String pathnew=format1.format(new Date());
	                  String fileName=files[i].getOriginalFilename();
	                  String suffer=fileName.substring(fileName.lastIndexOf("."));
	                  arrStr[i]="uploads/"+aa+"/"+pathnew+suffer;                 
	                  File targetFile = new File(path);  
	                  if(!targetFile.exists())
	                  {  
	                      targetFile.mkdirs();  
	                  }  
	                  FileOutputStream os = new FileOutputStream(path+"/"+pathnew+suffer);  
	                
	                  //FileInputStream in = (FileInputStream) files[i].getInputStream();  
	                  InputStream  in = files[i].getInputStream(); 
	                  new FileUpToServer();
	                  ChannelSftp sftp=FileUpToServer.connect(FTP_ADDRESS, Integer.parseInt(FTP_PORT), FTP_USERNAME, FTP_PASSWORD);

	                  FileUpToServer.upload(FTP_BASEPATH+"/uploads/"+aa, "",sftp,in,pathnew+suffer);   
	                  sftp.disconnect();
	                  //20170523
	                
	                 int b = 0;  
	//                 int len=-1;
	//                 byte[] bt = new byte[1024]; 
	//                 while((len=(in.read(bt))) != -1)      {
	//                     os.write(bt,0,len);                   
	//               }
	                 while((b=in.read()) != -1)
	                 {  
	                      os.write(b);  
	                 }  
	                  os.flush();  
	                  os.close();  
	                  in.close();                     
	             } catch (Exception e)
	             {  
	                  e.printStackTrace();  
	                 
	              }  
	        } 
	          
	      }  
	       return arrStr;
	  }  
		  
		  
		  /***
		   * 
		  * @Title: uploadFileToLocal
		  * @Description:上传文件至服务器LOCAL目录
		  * @param @param files
		  * @param @param request
		  * @param @return    参数
		  * @return String[]    返回类型
		  * @author yangqin01
		  * @throws
		   */
		  public static   String[] uploadFileToLocal(CommonsMultipartFile[] files,HttpServletRequest request)
		  { 		 
	       String[] arrStr=new String[files.length]; 
	       for(int i = 0;i<files.length;i++)
	       {  
	          if(!files[i].isEmpty())
	          {  
	              System.currentTimeMillis();  
	              try
	              {  
	            	  SimpleDateFormat format =new SimpleDateFormat("yyyyMMdd");
	          		  SimpleDateFormat format1 =new SimpleDateFormat("yyyyMMddHHmmssSSS");
	          		  new Date();                                
	                  String aa=format.format(new Date());
	                  String path = request.getSession().getServletContext().getRealPath("uploads")+"/"+aa;
	                  String pathnew=format1.format(new Date());
	                  String fileName=files[i].getOriginalFilename();
	                  String suffer=fileName.substring(fileName.lastIndexOf("."));
	                  arrStr[i]="uploads/"+aa+"/"+pathnew+suffer;                 
	                  File targetFile = new File(path);  
	                  if(!targetFile.exists())
	                  {  
	                      targetFile.mkdirs();  
	                  }  
	                  InputStream  in = files[i].getInputStream(); 
	                  
	                  File file = new File(FTP_BASEPATH_LOCAL+"\\uploads\\"+aa);
	                  fileExists(file);
	                  
	                  path= FTP_BASEPATH_LOCAL+"\\uploads\\"+aa+"\\"+pathnew+suffer;
	                  
	                  writeToLocal(path,in);
	                  
	                  in.close();                     
	             } catch (Exception e)
	             {  
	                  e.printStackTrace();  
	              }  
	        } 
	      }  
	       return arrStr;
	  }	  
		  
	/**
	 * 下载
	 * */  
  public static void download(String fileName, HttpServletRequest request, HttpServletResponse response)  throws Exception 
  {
	  //String fileName1=request.getParameter("fileName");
      response.setContentType("text/html;charset=utf-8");  
      request.setCharacterEncoding("UTF-8");  
      java.io.BufferedInputStream bis = null;  
      java.io.BufferedOutputStream bos = null;  

//      String ctxPath = request.getSession().getServletContext().getRealPath(  
//              "")  
//              + "/";  
      String downLoadPath = FTP_BASEPATH_LOCAL + fileName;
      Logger logger = Logger.getLogger(FileUtil.class); 
      logger.error(downLoadPath);
      String[] s=fileName.split("/");
      String name=s[s.length-1];
      System.out.println(downLoadPath);  
      try {  
          long fileLength = new File(downLoadPath).length();  
          response.setContentType("application/x-msdownload;");  
          response.setHeader("Content-disposition", "attachment; filename="  
                  + new String(name.getBytes("utf-8"), "ISO8859-1"));  
          response.setHeader("Content-Length", String.valueOf(fileLength));  
          bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
          bos = new BufferedOutputStream(response.getOutputStream());  
          byte[] buff = new byte[2048];  
          int bytesRead;  
          while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
              bos.write(buff, 0, bytesRead);  
          }  
      } catch (Exception e) {  
          e.printStackTrace();  
      } finally {  
          if (bis != null)  
              bis.close();  
          if (bos != null)  
              bos.close();  
      }  
        
  }  
  
  /**
   * 删除文件，可以是文件或文件夹
   *
   * @param fileName   要删除的文件名
   *         
   * @return 删除成功返回true，否则返回false
   */
  public static boolean delete(String fileName, HttpServletRequest request) {
	  request.getSession().getServletContext().getRealPath(  
              "");  
       fileName = FTP_BASEPATH_LOCAL + fileName;
      File file = new File(fileName);
      if (!file.exists()) {
          System.out.println("删除文件失败:" + fileName + "不存在！");
          return false;
      } else {
          if (file.isFile())
              return deleteFile(fileName);
          else
              return deleteDirectory(fileName);
      }
  }

  /**
   * 删除单个文件
   *
   * @param fileName 要删除的文件的文件名
   *           
   * @return 单个文件删除成功返回true，否则返回false
   */
  public static boolean deleteFile(String fileName) {
      File file = new File(fileName);
      // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
      if (file.exists() && file.isFile()) {
          if (file.delete()) {
              System.out.println("删除单个文件" + fileName + "成功！");
              return true;
          } else {
              System.out.println("删除单个文件" + fileName + "失败！");
              return false;
          }
      } else {
          System.out.println("删除单个文件失败：" + fileName + "不存在！");
          return false;
      }
  }

  /**
   * 删除目录及目录下的文件
   *
   * @param dir 要删除的目录的文件路径
   *            
   * @return 目录删除成功返回true，否则返回false
   */
  public static boolean deleteDirectory(String dir) {
      // 如果dir不以文件分隔符结尾，自动添加文件分隔符
      if (!dir.endsWith(File.separator))
          dir = dir + File.separator;
      File dirFile = new File(dir);
      // 如果dir对应的文件不存在，或者不是一个目录，则退出
      if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
          System.out.println("删除目录失败：" + dir + "不存在！");
          return false;
      }
      boolean flag = true;
      // 删除文件夹中的所有文件包括子目录
      File[] files = dirFile.listFiles();
      for (int i = 0; i < files.length; i++) {
          // 删除子文件
          if (files[i].isFile()) {
              flag = FileUtil.deleteFile(files[i].getAbsolutePath());
              if (!flag)
                  break;
          }
          // 删除子目录
          else if (files[i].isDirectory()) {
              flag = FileUtil.deleteDirectory(files[i]
                      .getAbsolutePath());
              if (!flag)
                  break;
          }
      }
      if (!flag) {
          System.out.println("删除目录失败！");
          return false;
      }
      // 删除当前目录
      if (dirFile.delete()) {
          System.out.println("删除目录" + dir + "成功！");
          return true;
      } else {
          return false;
      }
  }

  /**
   * 新的上传文件程序
   * @param CommonsMultipartFile[] files
   * @return String[]文件存储路径数组
   * @author 王增瑞
   * */
  @SuppressWarnings("resource")
public static   String[] uploadFile1(CommonsMultipartFile[] files,HttpServletRequest request)
  { 		 
   String[] arrStr=new String[files.length]; 
   for(int i = 0;i<files.length;i++)
   {  
    // System.out.println("fileName---------->" + files[i].getOriginalFilename());           
      if(!files[i].isEmpty())
      {  
          System.currentTimeMillis();  
          try
          {  
              //拿到输出流，同时重命名上传的文件  
        	  SimpleDateFormat format =new SimpleDateFormat("yyyyMMdd");
      		  SimpleDateFormat format1 =new SimpleDateFormat("yyyyMMddHHmmssSSS");
      		  new Date();                                
              String aa=format.format(new Date());
              String path = request.getSession().getServletContext().getRealPath("uploads")+"/"+aa;
              String pathnew=format1.format(new Date());
              String fileName=files[i].getOriginalFilename();
              String suffer=fileName.substring(fileName.lastIndexOf("."));
             // arrStr[i]="uploads/"+aa+"/"+pathnew+suffer;                 
              File targetFile = new File(path);  
              if(!targetFile.exists())
              {  
                  targetFile.mkdirs();  
              }  
              new FileOutputStream(path+"/"+pathnew+suffer);  
              //拿到上传文件的输入流  
              //FileInputStream in = (FileInputStream) files[i].getInputStream();  
              //InputStream  in = files[i].getInputStream(); 
              MultipartFile uploadFile=files[i];
              new FileUpToServer();
              ChannelSftp sftp= FileUpToServer.connect(FTP_ADDRESS, Integer.parseInt(FTP_PORT),FTP_USERNAME, FTP_PASSWORD);
              FileUpToServer.upload(FTP_BASEPATH+"/uploads/"+aa, "",sftp, uploadFile.getInputStream(),pathnew+suffer);  
              sftp.disconnect();
             // arrStr[i]= IMAGE_BASE_URL +"/uploads/"+ aa +"/"+ pathnew+suffer;
              arrStr[i]= "uploads/"+ aa +"/"+ pathnew+suffer;
          } catch (Exception e)
         {  
              e.printStackTrace();  
              System.out.println("上传出错");  
          }  
    } 
      
  }  
   return arrStr;
} 

  public static void newdownload(String fileName,String orgName, HttpServletRequest request, HttpServletResponse response)  throws Exception 
  {
	  //String fileName1=request.getParameter("fileName");
      response.setContentType("text/html;charset=utf-8");  
      request.setCharacterEncoding("UTF-8");  
      java.io.BufferedInputStream bis = null;  
      java.io.BufferedOutputStream bos = null;        
      String downLoadPath = FTP_BASEPATH_LOCAL +"/"+ fileName;   
       
      
      try {  
          long fileLength = new File(downLoadPath).length();  
          response.setContentType("application/x-msdownload;");  
          response.setHeader("Content-disposition", "attachment; filename="  
                  + new String(orgName.getBytes("utf-8"), "ISO8859-1"));  
          response.setHeader("Content-Length", String.valueOf(fileLength));  
          bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
          bos = new BufferedOutputStream(response.getOutputStream());  
          byte[] buff = new byte[2048];  
          int bytesRead;  
          while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
              bos.write(buff, 0, bytesRead);  
          }  
      } catch (Exception e) {  
          e.printStackTrace();  
      } finally {  
          if (bis != null)  
              bis.close();  
          if (bos != null)  
              bos.close();  
      }  
        
  }  
  
  /**
   * 上传文件
   * @param CommonsMultipartFile[] files
   * @return List
   * 
   * */
  public static   List<Map<String,Object>> uploadFileMap(CommonsMultipartFile[] files,HttpServletRequest request)
  { 		 
   //String[] arrStr=new String[files.length]; 
   List<Map<String,Object>> lmp=new ArrayList<>();
   for(int i = 0;i<files.length;i++)
   {  
    // System.out.println("fileName---------->" + files[i].getOriginalFilename());           
      if(!files[i].isEmpty())
      {  
    	  Map<String, Object> m=new HashMap<String, Object>();
    	  float len=files[i].getSize()/1024f;
    	  m.put("size", len);
          System.currentTimeMillis();  
          try
          {  
             
        	  SimpleDateFormat format =new SimpleDateFormat("yyyyMMdd");
      		  SimpleDateFormat format1 =new SimpleDateFormat("yyyyMMddHHmmssSSS");
      		  new Date();                                
              String aa=format.format(new Date());
              String path = request.getSession().getServletContext().getRealPath("uploads")+"/"+aa;
              String pathnew=format1.format(new Date());
              String fileName=files[i].getOriginalFilename();
              String suffer=fileName.substring(fileName.lastIndexOf("."));
             // arrStr[i]="uploads/"+aa+"/"+pathnew+suffer;  
              m.put("path", "uploads/"+aa+"/"+pathnew+suffer);
              File targetFile = new File(path);  
              if(!targetFile.exists())
              {  
                  targetFile.mkdirs();  
              }  
              FileOutputStream os = new FileOutputStream(path+"/"+pathnew+suffer);  
              
              InputStream  in = files[i].getInputStream(); 
              new FileUpToServer();
              FileUpToServer.upload(FTP_BASEPATH+"/uploads/"+aa, "",FileUpToServer.connect(FTP_ADDRESS, Integer.parseInt(FTP_PORT), FTP_USERNAME, FTP_PASSWORD),in,pathnew+suffer);
            
             int b = 0;  
//             int len=-1;
//             byte[] bt = new byte[1024]; 
//             while((len=(in.read(bt))) != -1)      {
//                 os.write(bt,0,len);                    
//           }
             while((b=in.read()) != -1)
             {  
                  os.write(b);  
             }  
              os.flush();  
              os.close();  
              in.close();                     
         } catch (Exception e)
         {  
              e.printStackTrace();  
            
          }  
          lmp.add(m);
    } 
      
  }  
   return lmp;
} 
  /**
   * 删除文件夹
   * @param String directory 文件的目录
   * @param String deleteFile  要删除的文件
   * @return void
   * 
   * */
  public static void sftpdelete(String directory, String deleteFile){
	  new FileUpToServer(); 
	  ChannelSftp sftp=FileUpToServer.connect(FTP_ADDRESS, Integer.parseInt(FTP_PORT), FTP_USERNAME, FTP_PASSWORD);
	  FileUpToServer.delete(FTP_BASEPATH+directory, deleteFile, sftp);	
	  sftp.disconnect();
  }
  
  private static void writeToLocal(String destination, InputStream input)
			throws IOException {
		int index;
		byte[] bytes = new byte[1024];
		FileOutputStream downloadFile = new FileOutputStream(destination);
		while ((index = input.read(bytes)) != -1) {
			downloadFile.write(bytes, 0, index);
			downloadFile.flush();
		}
		downloadFile.close();
		input.close();
	}


public static void fileExists(File file){
	  //如果文件夹不存在则创建    
	  if(!file .exists() && !file.isDirectory())      
	  {       
		  System.out.println("//不存在");  
		  file .mkdir();    
	  } else   
	  {  
		  System.out.println("//目录存在");  
	  }  
}
}